package com.fanghuaman.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fanghuaman.common.exception.FanghuamanException;
import com.fanghuaman.common.util.SecurityUtil;
import com.fanghuaman.model.common.emus.HttpEmus;
import com.fanghuaman.model.common.vo.ResponseResult;
import com.fanghuaman.model.user.dto.ProductDto;
import com.fanghuaman.model.user.pojo.ShoppingCart;
import com.fanghuaman.model.user.pojo.ShoppingCartHistory;
import com.fanghuaman.user.mapper.ShoppingCartHistoryMapper;
import com.fanghuaman.user.mapper.ShoppingCartMapper;
import com.fanghuaman.user.service.ShoppingCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author smh
 * @since 2024-12-08
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private ShoppingCartHistoryMapper shoppingCartHistoryMapper;


    /**
     * 添加购物车
     *
     * @param productDto
     * @return
     */
    @Override
    public ResponseResult addCart(ProductDto productDto) {
        // 获取用户信息
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SecurityUtil.User user = SecurityUtil.getUser(principal.toString());

        if (user == null || user.getId() == null) {
            return ResponseResult.fail("未登录");
        }

        // 添加购物车
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(user.getId());
        shoppingCart.setProductId(productDto.getId());
        shoppingCart.setProductSpecs(productDto.getSpaces());
        shoppingCart.setProductNum(productDto.getNumber());
        shoppingCart.setProductPrice(productDto.getPrice());
        shoppingCart.setProductName(productDto.getName());
        shoppingCart.setProductUrl(productDto.getImgUrl());
        shoppingCart.setCreateTime(new Date());
        shoppingCart.setUpdateTime(new Date());
        shoppingCart.setStatus(0);

        // 计算支付金额
        shoppingCart.setPayPrice(productDto.getPrice() * productDto.getNumber());

        int insert = shoppingCartMapper.insert(shoppingCart);
        if (insert > 0) {
            return ResponseResult.success("添加成功");
        }
        return ResponseResult.fail("添加失败");
    }

    @Override
    public ResponseResult getCart() {
        // 获取用户信息
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SecurityUtil.User user = SecurityUtil.getUser(principal.toString());

        if (user == null || user.getId() == null) {
            return ResponseResult.fail("未登录");
        }

        // 查询购物车
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(Wrappers.lambdaQuery(ShoppingCart.class).eq(ShoppingCart::getUserId, user.getId()));

        if (shoppingCarts == null) {
            return ResponseResult.success(Collections.emptyList());
        }

        return ResponseResult.success(shoppingCarts);
    }

    /**
     * 删除购物车商品
     *
     * @param cartId
     * @return
     */
    @Override
    public ResponseResult delCart(Long cartId) {
        // 获取用户信息
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SecurityUtil.User user = SecurityUtil.getUser(principal.toString());
        if (user == null || user.getId() == null) {
            return ResponseResult.fail("未登录");
        }
        ShoppingCart shoppingCart = shoppingCartMapper.selectOne(Wrappers.lambdaQuery(ShoppingCart.class).eq(ShoppingCart::getId, cartId).eq(ShoppingCart::getUserId, user.getId()));
        if (shoppingCart == null) {
            return ResponseResult.fail("购物记录不存在");
        }
        int i = shoppingCartMapper.deleteById(cartId);
        if (i > 0) {
            return ResponseResult.success("删除成功");
        }
        return null;
    }

    /**
     * 清空购物车
     *
     * @return
     */
    @Override
    public ResponseResult clearCart() {
        // 获取用户信息
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SecurityUtil.User user = SecurityUtil.getUser(principal.toString());
        if (user == null || user.getId() == null) {
            return ResponseResult.fail("未登录");
        }
        // 清空购物车
        int i = shoppingCartMapper.delete(Wrappers.lambdaQuery(ShoppingCart.class).eq(ShoppingCart::getUserId, user.getId()));
        if (i > 0) {
            return ResponseResult.success("清空成功");
        }
        return ResponseResult.fail("清空失败");
    }

    /**
     * 清空购物车,并记录历史信息
     *
     * @return
     */
    @Override
    public ResponseResult paid() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SecurityUtil.User user = SecurityUtil.getUser(principal.toString());
        if (user == null || user.getId() == null) {
            return ResponseResult.fail("未登录");
        }
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(Wrappers.lambdaQuery(ShoppingCart.class).eq(ShoppingCart::getUserId, user.getId()));

        // 记录到历史信息
        List<ShoppingCartHistory> shoppingCartHistories = shoppingCarts.stream().map(shoppingCart -> {
            ShoppingCartHistory shoppingCartHistory = new ShoppingCartHistory();
            BeanUtils.copyProperties(shoppingCart, shoppingCartHistory);

            shoppingCartHistory.setStatus(1);
            shoppingCartHistory.setPayTime(LocalDateTime.now());
            return shoppingCartHistory;
        }).collect(Collectors.toList());

        // 插入历史记录
        shoppingCartHistoryMapper.insertBatch(shoppingCartHistories);

        // 删除购物车
        int i1 = shoppingCartMapper.delete(Wrappers.lambdaQuery(ShoppingCart.class).eq(ShoppingCart::getUserId, user.getId()));
        if (i1 < 0) {
            throw new FanghuamanException(HttpEmus.FAIL);
        }

        return ResponseResult.success();
    }

    /**
     * 修改购物车
     *
     * @param cartId
     * @param productDto
     * @return
     */
    @Override
    public ResponseResult updateCart(Long cartId, ProductDto productDto) {

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SecurityUtil.User user = SecurityUtil.getUser(principal.toString());
        if (user == null || user.getId() == null) {
            return ResponseResult.fail("未登录");
        }

        if (cartId == null) {
            return ResponseResult.fail("购物车ID不能为空");
        }
        if (productDto == null) {
            return ResponseResult.fail("商品信息不能为空");
        }
        if (productDto.getNumber() <= 0) {
            return ResponseResult.fail("商品数量不能为空");
        }
        if (productDto.getPrice() <= 0) {
            return ResponseResult.fail("商品价格不能为空");
        }

        int update = shoppingCartMapper.update(null, Wrappers.lambdaUpdate(ShoppingCart.class)
                .eq(ShoppingCart::getId, cartId)
                .set(ShoppingCart::getProductPrice, productDto.getPrice())
                .set(ShoppingCart::getProductNum, productDto.getNumber())
                .set(ShoppingCart::getPayPrice, productDto.getPrice() * productDto.getNumber())
                .set(ShoppingCart::getProductSpecs, productDto.getSpaces()));
        if (update > 0) {
            return ResponseResult.success("修改成功");
        }
        return ResponseResult.fail("修改失败");
    }
}
